home *** CD-ROM | disk | FTP | other *** search
Java Source | 2002-08-09 | 3.3 KB | 108 lines |
- /*
- * 01/09/2002 - 20:43:57
- *
- * FileDownloader.java -
- * Copyright (C) 2002 Csaba KertΘsz
- * kcsaba@jdictionary.info
- * www.jdictionary.info
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-
- package info.jdictionary;
-
- import javax.swing.JProgressBar;
- import javax.swing.SwingUtilities;
- import java.net.URL;
- import java.io.DataInputStream;
-
-
- public class FileDownloader {
-
- public boolean stop = false;
-
-
- public void terminate() {
- stop = true;
- }
-
-
- public byte[] download(URL url, JProgressBar progressBar) {
- if(url == null)
- return null;
- DataInputStream din = null;
- int offset = 0;
- int length = 1024;
- int temp = 0;
- int fileSize = 0;
- try {
- fileSize = url.openConnection().getContentLength();
- din = new DataInputStream(url.openStream());
- }
- catch (java.lang.Exception e) {
- e.printStackTrace();
- return null;
- }
- if(progressBar != null) {
- progressBar.setMaximum(fileSize);
- progressBar.setMinimum(0);
- }
- byte[] b = new byte[fileSize];
-
- while (true) {
- try {
- if (stop) {
- din.close();
- return null;
- }
- temp = din.read(b, offset, length);
- if (temp == -1) {
- try {
- din.close();
- }
- catch(java.io.IOException e) {}
- return b;
- }
- offset = offset + temp;
- if (fileSize - offset < length)
- length = fileSize - offset;
- notifyProgressBar(progressBar, offset, fileSize);
- }
- catch(java.lang.Exception e) {
- e.printStackTrace();
- try {
- din.close();
- }
- catch(java.lang.Exception ex) {}
- return null;
- }
- }
- }
-
-
- void notifyProgressBar(final JProgressBar progressBar, final int currentState, final int topValue) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- if (progressBar != null) {
- progressBar.setValue(currentState);
- progressBar.setString(currentState / 1024 + " " + JDictionary.getString("KB of") + " " + topValue / 1024 + " " + JDictionary.getString("KB"));
- progressBar.validate();
- progressBar.repaint();
- }
- }
- });
- }
- }